package com.ctrip.demo.lock;

import java.util.Arrays;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xs.wu
 */
public class CyclicBarrierTest {

    private static int sum1;
    static int sum2 = 0;
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
        // 当计数器为0时，立即执行
        @Override
        public void run() {
            System.out.println(sum1 == sum2);
            System.out.println("汇总线程：" + Thread.currentThread().getName() + " 任务合并。");
        }
    });

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {


        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 将线程A添加到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("线程A：" + Thread.currentThread().getName() + "执行任务。");
                    System.out.println("线程A：到达屏障点");

                    for (int i = 0; i < 10; i++) {
                        sum1 += i ;
                    }
                    cyclicBarrier.await();
                    System.out.println("线程A：退出屏障点");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // 将线程B添加到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("线程B：" + Thread.currentThread().getName() + "执行任务。");
                    System.out.println("线程B：到达屏障点");

                    for (int i = 0; i < 10; i++) {
                        sum2 += i;
                    }
                    cyclicBarrier.await();
                    System.out.println("线程B：退出屏障点");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });



        // 关闭线程池
        executorService.shutdown();
    }

}
